package app;

import java.io.File;

import org.rygh.core.html.Html;
import org.rygh.core.util.UIo;
import org.rygh.core.xml.XmlLeaf;

import wsi.exp.Exp1SelectedTree;
import wsi.exp.Exp2TreeToEntity;
import wsi.exp.Exp4WebCallRatio;
import wsi.exp.ExpFolderController;
import wsi.exp.Experiment;
import wsi.exp.exp3.Exp3PathMatchByPair;
import wsi.exp.exp3.Exp3PathMatchByPred;
import wsi.function.Function;
import wsi.function.FunctionController;
import wsi.function.RuntimeInfo;
import wsi.resolve.Aggregator;
import wsi.script.AppConfig;
import wsi.script.AppTag;
import wsi.script.AppXml;
import wsi.task.Engine;

public class wsi extends App {

	private static void compare(Experiment exp) {
		exp.compute();
		exp.save();
	}

	public static void main(String[] args) {
		init();

		if (args.length > 0)
			run(args[0]);
		else
			run(AppXml.DEFAULT_FILE);

		bye();
	}

	private static void run(String filePath) {
		AppConfig.init(filePath);

		AppConfig ac = AppConfig.shared();
		System.out.print(ac.toString());

		Engine engine = new Engine();
		FunctionController fctrl = FunctionController.shared();
		Function function;
		RuntimeInfo iconfig;
		String service, func_name;

		for (XmlLeaf serviceNode : ac.getOnServices()) {
			service = serviceNode.getValue().getAttribute(AppTag.name);

			for (XmlLeaf functionNode : ac.getOnFunctions(serviceNode)) {
				func_name = functionNode.getValue().getAttribute(AppTag.name);

				function = fctrl.getFunction(service, func_name);
				assert function != null : String.format("%s/%s", service,
						func_name);

				iconfig = new RuntimeInfo(function, functionNode);

				function.setup(iconfig);
				engine.process(function);

				System.gc();
			}
		}

		compare(new Exp1SelectedTree());
		compare(new Exp2TreeToEntity());
		compare(new Exp3PathMatchByPair());
		compare(new Exp3PathMatchByPred());
		compare(new Exp4WebCallRatio());

		saveMatchLog();
	}

	private static void saveMatchLog() {
		Html html = new Html("Match Log");
		html.addElement(Aggregator.toMatchInfoTable());

		File dir = ExpFolderController.shared().getFolderForExp2Debug();

		UIo.saveFile(new File(dir, "_debug_match_log.html"), html.toString());
	}
}
